//
//  MBBuyHeadController.m
//  LiveBroadcast
//
//  Created by 肖剑 on 2019/5/8.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBBuyHeadController.h"
#import <AlipaySDK/AlipaySDK.h>

@interface MBBuyHeadController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageV;
@property (weak, nonatomic) IBOutlet UILabel *titleLbl;
@property (weak, nonatomic) IBOutlet UILabel *timeLbl;
@property (weak, nonatomic) IBOutlet UITextField *findTF;

@property (weak, nonatomic) IBOutlet UITextField *cityTF;
@property (weak, nonatomic) IBOutlet UILabel *payMoneyLbl;
@property (weak, nonatomic) IBOutlet UIButton *payBtn;

@property (assign,nonatomic)NSInteger currentFindTag;
@property (assign,nonatomic)NSInteger currentCityTag;

@property (copy,nonatomic)NSString *findString;
@property (copy,nonatomic)NSString *cityString;

@end

@implementation MBBuyHeadController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.findTF.delegate = self;
    self.cityTF.delegate = self;
    self.title = @"购买头条";
    
    self.payMoneyLbl.text = @"";
    self.currentFindTag = 11000;
    [self findClick:(UIButton *)[self.view viewWithTag:11000]];
    
    self.currentCityTag = 21000;
    [self cityClick:(UIButton *)[self.view viewWithTag:21000]];
    
    NSLog(@"MBBuyHeadController  dict ====== %@",self.dict);
    
    self.titleLbl.text = self.dict[@"videoLabel"];
    self.timeLbl.text = [self getTime:self.dict[@"issueTime"]];
    
    [self.imageV sd_setImageWithURL:[NSURL URLWithString:self.dict[@"coverUrl"]]];
    
    
}

- (NSString *)getTime:(NSString *)time
{
    NSTimeInterval interval    =[time doubleValue] / 1000.0;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.findTF) {
        self.findString = textField.text;
    }else{
        self.cityString = textField.text;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == self.findTF) {
        self.findString = textField.text;
    }else{
        self.cityString = textField.text;
    }
}




- (IBAction)findClick:(UIButton *)sender {
    
    UIButton *button = (UIButton *)[self.view viewWithTag:self.currentFindTag];
    [self.view endEditing:YES];
    if ([sender.currentTitle isEqualToString:@"自定义"]) {
        self.findTF.hidden = NO;
    }else{
        if ([sender.currentTitle containsString:@"万"]) {
            self.findString = [sender.currentTitle stringByReplacingOccurrencesOfString:@"万" withString:@"0000"];
            if ([sender.currentTitle containsString:@"."]) {
                self.findString = [sender.currentTitle stringByReplacingOccurrencesOfString:@"万" withString:@"000"];
                self.findString = [self.findString stringByReplacingOccurrencesOfString:@"." withString:@""];
            }
        }else{
            self.findString = sender.currentTitle;
        }
        self.findTF.hidden = YES;
    }
    
    
    if (sender == button) return;
    sender.backgroundColor = self.payBtn.backgroundColor;
    button.backgroundColor = kColorRGBA(188, 188, 188, 1);
    self.currentFindTag = sender.tag;
    
    
    
}

- (IBAction)cityClick:(UIButton *)sender {
    UIButton *button = (UIButton *)[self.view viewWithTag:self.currentCityTag];
    [self.view endEditing:YES];
    
    if ([sender.currentTitle isEqualToString:@"自定义"]) {
        self.cityTF.hidden = NO;
    }else{
        
        if ([sender.currentTitle containsString:@"万"]) {
            self.cityString = [sender.currentTitle stringByReplacingOccurrencesOfString:@"万" withString:@"0000"];
            if ([sender.currentTitle containsString:@"."]) {
                self.cityString = [sender.currentTitle stringByReplacingOccurrencesOfString:@"万" withString:@"000"];
                self.cityString = [self.cityString stringByReplacingOccurrencesOfString:@"." withString:@""];
            }
        }else{
            self.cityString = sender.currentTitle;
        }
        self.cityTF.hidden = YES;
    }
    
    if (sender == button) return;
    sender.backgroundColor = self.payBtn.backgroundColor;
    button.backgroundColor = kColorRGBA(188, 188, 188, 1);
    self.currentCityTag = sender.tag;
}

- (IBAction)payClick {
    
    CGFloat money = [self.findString floatValue] + [self.cityString floatValue];
//    self.payMoneyLbl.text = [NSString stringWithFormat:@"%.2f",money];
    
    self.payMoneyLbl.text = @"0.01";
    
    NSLog(@"self.findString = %@",self.findString);
    NSLog(@"self.cityString = %@",self.cityString);
    [MBHttpRequset requestWithUrl:kTradeid_userCenter_buyHotHeadlines setParams:@{@"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId),@"videoId":filter(self.dict[@"id"]),@"foundShow":self.findString,@"withShow":self.cityString,@"payment":self.payMoneyLbl.text,@"type":@"3"} isShowProgressView:NO success:^(id  _Nonnull AJson) {
        
        NSLog(@"kTradeid_pay_alipayRequest = %@",AJson);
        [MBHttpRequset requestWithUrl:kTradeid_pay_alipayRequest setParams:@{@"outTradeNo":AJson[@"orderNo"],@"payType":@"3"} isShowProgressView:NO success:^(id  _Nonnull AJson) {
            NSLog(@"kTradeid_pay_alipayRequest = %@",AJson);
            
            [self AliPay:AJson];
        } failure:^(id  _Nonnull AJson) {
            
        }];
    } failure:^(id  _Nonnull AJson) {
        
    }];
    
}

- (void)AliPay:(NSString *)key
{
    // 重要说明
    // 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    // 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    // 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"2019021463212882";
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = key;
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"缺少appId或者私钥,请检查参数设置"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *action){
                                                           
                                                       }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{ }];
        return;
    }
    
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:key fromScheme:@"alipay" callback:^(NSDictionary *resultDic) {
        NSString *resultS = resultDic[@"result"];
        if (resultS.length == 0) {
            [MBProgressHUD showError:resultDic[@"memo"]];
        }
        NSLog(@"reslut = %@",resultDic);
    }];
}
@end
